package com.itheima.reggie.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.File;
import java.time.LocalDateTime;

@Configuration
public class DeleteImgTask {

    @Value("${reggie.path}")
    private String imgPath;

    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;

    @Scheduled(cron = "0 0 */1 * * *")
    public void deleteImg() {
        System.out.println("定时任务: " + LocalDateTime.now());
        File file = new File(imgPath);
        File[] files = file.listFiles();
        for (File f : files) {
            if (f.isDirectory()) {
                System.out.println("文件夹: " + f.getName());
            } else {
                System.out.println("文件: " + f.getName());
                LambdaQueryWrapper<Dish> dishWrapper = new LambdaQueryWrapper<>();
                dishWrapper.eq(Dish::getImage, f.getName());
                int dishCount = dishService.count(dishWrapper);
                LambdaQueryWrapper<Setmeal> setmealWrapper = new LambdaQueryWrapper<>();
                setmealWrapper.eq(Setmeal::getImage, f.getName());
                int setmealCount = setmealService.count(setmealWrapper);
                if (dishCount == 0 && setmealCount == 0) {
                    f.delete();
                }
            }
        }
    }

}